#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

struct ListNode {
    int val;
    struct ListNode* next;
    
};

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
    struct ListNode* newhead = NULL;
    struct ListNode* newtail = NULL;
    if (list1 == NULL)
    {
        return list2;
    }
    else  if (list2 == NULL)
    {
        return list1;
    }


    while (list1 && list2)
    {
        if (list1->val <= list2->val)
        {
            if (newhead == NULL)
            {
                newhead = newtail = list1;
                list1 = list1->next;
            }
            else
            {
                newtail->next = list1;
                newtail = list1;
                list1 = list1->next;
            }
        }
        else if (list1->val > list2->val)
        {
            if (newtail != NULL)
            {
                newtail->next = list2;
                newtail = list2;
                list2 = list2->next;
            }
            else
            {
                newhead = newtail = list2;
                list2 = list2->next;
            }


        }
    }
    if (list1)
    {
        while (list1)
        {
            newtail->next = list1;
            newtail = list1;
            list1 = list1->next;
        }


    }
    if (list2)
    {
        while (list2)
        {
            newtail->next = list2;
            newtail = list2;
            list2 = list2->next;
        }

    }

    return newhead;

}